<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>


    <!-- 卡片视图区域 -->
    <el-card>
        <!-- 警告区域 -->
        <el-alert title="注意: 只允许为第三级分类设置相关参数!" type="warning" :closable="false" show-icon></el-alert>

        <!-- 选择商品分类区域 -->
        <el-row class="el-otp">
            <el-col>
                <span> 选择商品分类: </span>
                <!-- 选择商品级联选择框 -->
                <!-- options 用来指定数据源 -->
                <!-- props 用来指定配置对象 -->
                <el-cascader v-model="selectedCateKeys" :options="cateList"  ref="example"
                :props="cateProps" @change="handleChange" clearable change-on-select>
                </el-cascader>
            </el-col>
        </el-row>

        <!-- tab页签区域 -->
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 添加动态参数的面板 -->
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" size="mini" :disabled="isDisabled" @click="addDialogVisible = true">添加参数</el-button>
                <!-- 动态参数表格 -->
                <el-table :data="manyTableData" style="width: 100%" border stripe>
                    <!-- 展开行 -->
                    <el-table-column type="expand">
                        <!-- 循环渲染tag标签 -->
                        <template v-slot="scope">
                            <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" @close="removeLabel(i,scope.row)" closable>{{item}}</el-tag>
                            <!-- 可输入的tag标签 -->
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                            </el-input>
                            <!-- 添加的按钮 -->
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <!-- 索引列 -->
                    <el-table-column type="index"></el-table-column>
                    <el-table-column prop="attr_name" label="参数名称">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="scope"> 
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="showRemovaDialog(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <!-- 添加静态属性的面板 -->
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" size="mini" :disabled="isDisabled" @click="addDialogVisible = true">添加属性</el-button>
                <!-- 静态属性表格 -->
                <el-table :data="onlyTableData" style="width: 100%" border stripe>
                    <!-- 展开行 -->
                    <el-table-column type="expand">
                        <!-- 循环渲染tag标签 -->
                        <template v-slot="scope">
                            <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" @close="removeLabel(i,scope.row)" closable>{{item}}</el-tag>
                            <!-- 可输入的tag标签 -->
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                            </el-input>
                            <!-- 添加的按钮 -->
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <!-- 索引列 -->
                    <el-table-column type="index"></el-table-column>
                    <el-table-column prop="attr_name" label="属性名称">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="scope"> 
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="showRemovaDialog(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
        :title="'添加'+tatilText"
        :visible.sync="addDialogVisible"
        width="50%" @close="addDialogClose">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
            <el-form-item :label="tatilText" prop="attr_name">
                <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
        </el-form>    
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog
        :title="'修改'+tatilText"
        :visible.sync="editDialogVisible"
        width="50%" @close="editDialogClose">
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px" >
            <el-form-item :label="tatilText" prop="attr_name">
                <el-input v-model="editForm.attr_name"></el-input>
            </el-form-item>
        </el-form>    
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name:'Params',
    data() {
        return {
            // 商品分类数据列表
            cateList:[],
            // 指定级联选择器的配置对象
            cateProps:{
                expandTrigger: 'hover' ,
                value:'cat_id',
                label:'cat_name',
                children:'children',
            },
            // 级联选择框双向绑定的数据
            selectedCateKeys:[],
            // 被激活tab页签名称
            activeName:'many',
            // 动态参数的相关数据
            manyTableData:[],
            // 静态属性的相关数据
            onlyTableData:[],
            // 控制添加对话框的显示与隐藏
            addDialogVisible:false,
            // 添加动态 静态表单数据对象
            addForm:{
                attr_name: ''
            },
            // 添加动态 静态表单验证规则
            addFormRules:{
                attr_name:[
                    { required: true, message: '请输入参数名称', trigger: 'blur' },
                    { min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur' }
                ]
            },    
            // 控制修改对话框的显示与隐藏
            editDialogVisible:false,
            // 修改的表单数据对象
            editForm:{},
            
        }
    },
    created() {
        this.getCateList()
    },
    computed:{
        // 控制添加 属性和参数按钮
        isDisabled(){
            if(this.selectedCateKeys.length !== 3){
                return true
            }
            return false
        },
        // 当前级联选择框选中三级商品的id
        cateId(){
            if(this.selectedCateKeys.length === 3){
                return this.selectedCateKeys[2]
            }
            return null
        },
        // 加参数的对话框的标题
        tatilText(){
            if(this.activeName === 'many'){
                return '动态参数'
            }else{
                return '静态属性'
            }
        }
    },
    methods: {
        //获取商品分类数据列表
        async getCateList(){
            const {data: res} = await this.$http.get('categories')
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.error('获取商品分类数据列表失败！');
            this.cateList = res.data
        },
        // 获取参数的列表数据
        async getParaemsData(){
            // console.log(this.selectedCateKeys);
            //如果 selectedCateKeys.length 不等于三 则选中的不是 三级分类
            if(this.selectedCateKeys.length!==3) {
                this.selectedCateKeys=[]
                //防止切换级联选择框中的内容时 选中的是 一级或二级 选择框里没有内容
                //而下方的数据没有清空 
                this.manyTableData=[]
                this.onlyTableData=[]
                this.$message.warning('只允许为第三级分类设置相关参数!')
                return
            }
            //根据所选分类的id获取相应参数数据
           const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel: this.activeName}})
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.error('获取商品数据失败！')
            res.data.forEach(item => {
               item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
               // 控制文本框的显示与隐藏
               item.inputVisible = false 
               // 文本框里输入的内容
               item.inputValue = ''
            });
            // console.log(res.data);
            if(this.activeName === 'many'){
                this.manyTableData = res.data
            }else{
                this.onlyTableData = res.data
            }
        },
        // 级联选择框选中项发生变化 会出发这个函数
        handleChange(){
            this.getParaemsData()
            // 自动关闭级联选择框
            this.$refs.example.toggleDropDownVisible();
        },
        // Tab页签点击事件处理函数
        handleTabClick(){
            // console.log(this.activeName);
            this.getParaemsData()
        },
        // 监听添加属性对话框的关闭事件
        addDialogClose(){
            // console.log(this.$refs);
            this.$refs.addFormRef.resetFields()
        },
        // 点击确定按钮 添加动态参数 静态属性
        async addParams(){
            // console.log(this.$refs);
            this.$refs.addFormRef.validate(async valid =>{
                // console.log(valid);
                if(!valid) return 
               const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`,{attr_name:this.addForm.attr_name,attr_sel:this.activeName})
               //console.log(res);
                if(res.meta.status !== 201){
                    return this.$message.error('添加失败！')
                }
                this.$message.success('添加成功！')
                this.addDialogVisible = false
                this.getParaemsData()
            })
        },
        // 修改按钮功能
        async showEditDialog(id){
            // console.log(id);
            const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${id}`,{params:{
                attr_sel:this.activeName
            }})
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.error('请求参数失败！')
            this.editForm = res.data
            // console.log(this.editForm);
            this.editDialogVisible = true
        },
        // 重置修改表单
        editDialogClose(){
            this.$refs.editFormRef.resetFields()
        },
        // 点击确定提交修改
        editParams(){
            this.$refs.editFormRef.validate(async valid =>{
                if(!valid) return
                const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{attr_name: this.editForm.attr_name,attr_sel:this.activeName})
                // console.log(res);
                if(res.meta.status !== 200) return this.$message.error('修改参数失败！')
                this.$message.success('修改参数成功！')
                // 这里调用 getParaemsData函数 重新获取参数的列表数据
                this.getParaemsData()
                this.editDialogVisible = false
            })
        },
        // 删除功能
        async showRemovaDialog(id){
           const removeConfirm = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'}).catch(err=>err)
            if(removeConfirm !== 'confirm') return this.$message.info('已取消删除操作！')
            const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.error('删除失败！')
            this.$message.success('删除成功！')
            this.getParaemsData()
        },
        // 文本框失去了焦点 或者按下了enter 都会触发
        async handleInputConfirm(row){
            if(row.inputValue.trim().length === 0) {
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = ''
            row.inputVisible = false
            // 发起请求 保存添加的内容
            this.saveAttrVals(row)
        },
        showInput(row){
            row.inputVisible = true
            //文本框自动获取焦点
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        // 将对attr_vals的操作保存到数据库
        async saveAttrVals(row){
            // 发起请求 保存添加的内容
            const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
            {attr_name: row.attr_name,attr_sel: row.attr_sel,attr_vals: row.attr_vals.join(' ')})
            if(res.meta.status !== 200) return this.$message.error('修改参数数据失败！')
            this.$message.success('修改参数数据成功！')
        },
        // 点击 X 删除对应的tag属性
        removeLabel(i,row){
            row.attr_vals.splice(i,1)
            this.saveAttrVals(row)
        }
    },
}
</script>

<style scoped>
    .el-otp{
        margin: 15px 0;
    }
    .el-tag{
        margin-right: 8px;
    }
    .input-new-tag{
        width: 120px;
    }
</style>